package com.topnav.mc.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.js.lib.cache.SysCache;
import com.js.lib.result.Result;
import com.topnav.mc.admin.entity.*;
import com.topnav.mc.admin.entity.bean.RoleAuthorizationBean;
import com.topnav.mc.admin.entity.enums.EnumLogType;
import com.topnav.mc.admin.entity.enums.EnumOperateFunction;
import com.topnav.mc.admin.entity.param.RoleAuthorizationParam;
import com.topnav.mc.admin.security.CustomLoginSuccess;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.security.jwt.utils.JwtTokenUtil;
import com.topnav.mc.admin.service.*;
import com.topnav.mc.common.Constant;
import com.topnav.mc.common.SysConfigKeyConstant;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ExceptionUtil;
import com.topnav.mc.uitls.PermissionGradeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 实现登录成功后的处理
 */
@Service
public class UserLoginSuccessImpl implements CustomLoginSuccess {
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SysCache sysCache;
    @Resource
    private PermissionGradeUtil permissionGradeUtil;
    @Autowired
    private IRoleAuthorizationService roleAuthorizationService;
    @Autowired
    private IAuthorizationService authorizationService;
    @Autowired
    private IUserOrganizaitonService userOrganizaitonService;
    @Autowired
    private IOperateLogService operateLogService;
/*    *//** 配置的token 有效分钟数 *//*
    @Value("${jwt.tokenValidity:180}")
    private Long tokenValidity;*/

    @Override
    public Object afterLoginSuccess(String loginName,String token) {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("loginName",loginName);
        User user = null;
        PermissionGrade permissionGrade = new PermissionGrade();
        if ("super".equals(loginName)){
            user = new User();
            user.setCode(loginName);
            user.setName("超级系统管理员");
            user.setLoginName(loginName);
            user.setEnabledNotify(true);
        }else{
            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("login_name",loginName);
            user = userService.getOne(wrapper,false);
        }
        /** 保存token 和用户的关联信息 */
        if (user != null){
            resultMap.put("userCode",user.getCode());
            resultMap.put("userName",user.getName());
            resultMap.put("fullName",user.getName());

            /** 用户 */
            permissionGrade.setUserId(user.getId());
            permissionGrade.setUserName(user.getLoginName());
            permissionGrade.setEnabledNotify(user.getEnabledNotify());
            /** 默认是普通人员 */
            permissionGrade.setPermissionLevel(1);
            /** 取当前登录单位*/
            Long oginOrgId = getLoginOrgId(user);
            if (oginOrgId != null){
                /** 机构 单位 */
                Organization organization = organizationService.getById(user.getLoginOrgId());
                if (organization != null){
                    resultMap.put("fullName",user.getName() + "(" + organization.getShortName() + ")") ;
                    //resultMap.put("fullName",loginName + "->" + organization.getShortName());
                    permissionGrade.setOrgId(organization.getId());
                    permissionGrade.setOrgPath(organization.getPath());
                    permissionGrade.setOrgName(organization.getShortName());
                }
                /** 在此单位的最高权限 */
                permissionGrade.setPermissionLevel(1);
                Role role = roleService.getOneHighLeveByUserOrgRole(user.getId(),user.getOrgId());
                if (role != null)
                    permissionGrade.setPermissionLevel(role.getRoleLevel());
            }else if ("admin".equals(user.getLoginName().toLowerCase()) || "super".equals(user.getLoginName().toLowerCase())){
                /** 超级管理默认最高级别 */
                permissionGrade.setPermissionLevel(9);
            }
            /** 过期时间 */
            Long tokenValidity = 180 * 60L;
            Date expireTime = jwtTokenUtil.getExpirationDateFromToken(token);
            if (expireTime != null){
                /** 取token 过期时间向后延5分钟，防止万一token未过期而取不到数据了 */
                tokenValidity = expireTime.getTime() - new Date().getTime() + 5*60L;
            }

            //查询ZZD登录的帐号密码
            Map<String,String> d3PartAcount = null;
            if (permissionGrade.getPermissionLevel() >= 9){
                Object obj=null;
                if ((obj= sysCache.hget(Constant.CACHE_KEY_SYSTEMCONFIG, SysConfigKeyConstant.GROUP_TALK_USER))!=null){
                    if (obj == null) return null;
                    SystemConfig sc = (SystemConfig)obj;
                    if (!StringUtils.isEmpty(sc.getSysValue()))
                        d3PartAcount = saveToMap(d3PartAcount,"account",sc.getSysValue());
                };
                if ((obj= sysCache.hget(Constant.CACHE_KEY_SYSTEMCONFIG, SysConfigKeyConstant.GROUP_TALK_PSWD))!=null){
                    if (obj == null) return null;
                    SystemConfig sc = (SystemConfig)obj;
                    if (!StringUtils.isEmpty(sc.getSysValue()))
                        d3PartAcount = saveToMap(d3PartAcount,"password",sc.getSysValue());
                };

            }else{
                LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
                String[] paths = permissionGrade.getOrgPath().split("/");
                for(int i=paths.length-1;i>=0;i--){
                    wrapper.clear();
                    wrapper.eq(Organization::getId,paths[i]);
                    Organization organization = organizationService.getOne(wrapper,false);
                    if (!StringUtils.isEmpty(organization.getGroupTalkUser()) && !StringUtils.isEmpty(organization.getGroupTalkPswd())){
                        d3PartAcount = saveToMap(d3PartAcount,"account",organization.getGroupTalkUser());
                        d3PartAcount = saveToMap(d3PartAcount,"password",organization.getGroupTalkPswd());
                        break;
                    }
                }
            }
            permissionGrade.setD3PartAcount(d3PartAcount);
            permissionGradeUtil.setPmGrade(token,permissionGrade,tokenValidity);

            //

            /** 取得单位列表并返回，在主页的菜单上显示，并能切换单位 */
            resultMap.put("organizations",organizationService.genOrgOfLoginUser(user));
            resultMap.put("permissionLevel",permissionGrade.getPermissionLevel());

            /** 菜单权限 功能权限 **/
            List<String> menus = new ArrayList<>();
            /** 取得菜单权限给前端*/
            if (permissionGrade.getPermissionLevel() >= 9){
                //超级系统管理员返回全部菜单
                List<Authorization> list =authorizationService.list();
                for(Authorization a : list){
                    menus.add(a.getAtCode());
                }
            }else{
                //根据当前用户的登录部门的权限来界定
                LambdaQueryWrapper<UserOrganizaiton> urWrapper = new  LambdaQueryWrapper<UserOrganizaiton>()
                        .eq(UserOrganizaiton::getUserId,permissionGrade.getUserId()).eq(UserOrganizaiton::getOrgId,permissionGrade.getOrgId());
                UserOrganizaiton uo = userOrganizaitonService.getOne(urWrapper,false);
                QueryWrapper<RoleAuthorizationParam> raWwrapper = new QueryWrapper<RoleAuthorizationParam>();
                raWwrapper.eq("ra.role_id",uo.getRoleId());
                raWwrapper.orderByAsc("a.at_path");
                List<RoleAuthorizationBean> list = roleAuthorizationService.listInfo(raWwrapper);
                for(RoleAuthorizationBean ra : list){
                    menus.add(ra.getAuthCode());
                }
            }
            resultMap.put("menus",menus);
        }

        //super 不保存日志
        if ("super".equals(loginName)){
            return resultMap;
        }
        //登录日志
        OperateLog operateLog = new OperateLog();
        operateLog.setClientIp(jwtTokenUtil.getClientIpFromToken(token));
        operateLog.setUserId(permissionGrade.getUserId());
        operateLog.setLogType(EnumLogType.LOGIN.getCode());
        operateLog.setFunctionId(EnumOperateFunction.SYSTEM.getCode());
        operateLog.setCreateBy(loginName);
        operateLogService.save(operateLog);
        return resultMap;
    }

    /**
     * 如果没有 LoginOrgId, LoginOrgId = orgId;
     * @param user
     * @return
     */
    private Long getLoginOrgId(User user){
        if (user == null){return null;}
        if (user.getLoginOrgId() != null) {return user.getLoginOrgId();}
        if (user.getOrgId()== null){return null;}

        user.setLoginOrgId(user.getOrgId());
        userService.updateById(user);
        return user.getLoginOrgId();
    }

    private Map<String, String> saveToMap(Map<String, String> map, String key,String value){
        if (map == null){
            map = new HashMap<>();
        }
        map.put(key,value);
        return map;
    }
}
